<template>
  <div class="h-70vh">
    <div class="h-60vh overflow-y-auto">
      <el-tree
        ref="treeRef"
        :data="ownPowerTree"
        :props="defaultProps"
        :expand-on-click-node="false"
        default-expand-all
        show-checkbox
        node-key="resourceId"
        :default-checked-keys="defaultCheckedKeys"
      />
    </div>
    <div class="flex gap-20 h-10vh items-center justify-center">
      <el-button :loading="loading" type="primary" @click="handleConfirm">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { systemApi } from '@/api'
import { convertArrayToTree } from './utils'

const props = defineProps<{
  roleId: string
}>()

const emit = defineEmits(['cancel'])

const ownPowerTree = ref<any[]>([])
const defaultProps = ref<any>({
  children: 'children',
  label: 'funcName',
  disabled: 'disabled',
})
const defaultCheckedKeys = ref<string[]>([])

const getPermissionList = async () => {
  const { succeed, model } = await systemApi.queryRoleAssignedList(props.roleId)
  if (succeed) {
    ownPowerTree.value = convertArrayToTree(model)
    defaultCheckedKeys.value = getLeafNodes(model)
      .filter(item => item.exFlag)
      .map(item => item.resourceId)
  }
}

const getLeafNodes = nodes => {
  return nodes.reduce((acc, node) => {
    if (!node.children || node.children.length === 0) {
      acc.push(node)
    } else {
      acc.push(...getLeafNodes(node.children))
    }
    return acc
  }, [])
}

onMounted(() => {
  getPermissionList()
})

//保存菜单权限
const treeRef = ref<any>(null)
const loading = ref(false)
const handleConfirm = async () => {
  const checkedKeys = treeRef?.value?.getCheckedNodes(false, true).map(item => item.resourceId)
  // 调用接口
  loading.value = true
  const { succeed } = await systemApi.assignUserPermission(props.roleId, {
    resourceIds: checkedKeys,
    sysType: '31',
  })
  loading.value = false
  if (succeed) {
    emit('cancel')
  }
}

// 取消保存
const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.page {
  width: 100%;
  height: 100%;
}
</style>
